package top.ajun.mall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ajun.common.utils.PageUtils;
import top.ajun.common.utils.Query;
import top.ajun.mall.product.dao.CategoryDao;
import top.ajun.mall.product.entity.CategoryEntity;
import top.ajun.mall.product.service.CategoryBrandRelationService;
import top.ajun.mall.product.service.CategoryService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
            new Query<CategoryEntity>().getPage(params),
            new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if (StrUtil.isNotEmpty(category.getName())) {
            // 如果要更新分类名称，则关联表中也需要进行级联更新
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

            // TODO 更新其它关联的分类信息
        }
    }

    @Override
    public void removeMenuByIds(List<Long> catIds) {
        // TODO 检查当前要删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(catIds);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return paths.toArray(new Long[parentPath.size()]);
    }

    /**
     * 递归查找当前三级分类的完整路径
     */
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity category = this.getById(catelogId);
        Long parentCid = category.getParentCid();
        if (parentCid != 0) {
            findParentPath(parentCid, paths);
        }
        return paths;
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查询出所有分类
        List<CategoryEntity> categories = baseMapper.selectList(Wrappers.emptyWrapper());

        // 组装成父子格式的树形结构
        return categories.stream()
            .filter(menu -> menu.getParentCid() == 0)
            .peek(menu -> menu.setChildren(getChildrenList(menu, categories)))
            .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
            .collect(Collectors.toList());
    }

    /**
     * 从所有菜单中找到当前菜单的子菜单(递归)
     *
     * @param root       当前菜单
     * @param categories 所有菜单
     * @return List 菜单列表
     */
    private List<CategoryEntity> getChildrenList(CategoryEntity root, List<CategoryEntity> categories) {
        return categories.stream()
            .filter(menu -> menu.getParentCid().equals(root.getCatId()))
            .peek(menu -> menu.setChildren(getChildrenList(menu, categories)))
            .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
            .collect(Collectors.toList());
    }

}